<template>
  <div class="text-tools">
    <ToolContainer
      tool-name="文本处理"
      title="强大的文本处理工具"
      description="支持多种文本格式化、编码转换和内容优化功能，让文本处理变得简单高效"
      :header-icon="Document"
      icon-color="#409EFF"
      default-tab="format"
      @tab-change="handleTabChange"
    >
      <template #tabs>
        <!-- 文本格式化标签页 -->
        <el-tab-pane label="文本格式化" name="format">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="text-input-section">
                <el-form label-width="100px">
                  <el-form-item label="输入文本">
                    <el-input
                      v-model="textInput"
                      type="textarea"
                      :rows="8"
                      placeholder="请输入要处理的文本..."
                      show-word-limit
                      maxlength="10000"
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleToUpperCase"
                :loading="loading"
                :disabled="!textInput.trim()"
              >
                转大写
              </el-button>
              <el-button 
                type="success" 
                @click="handleToLowerCase"
                :loading="loading"
                :disabled="!textInput.trim()"
              >
                转小写
              </el-button>
              <el-button 
                type="warning" 
                @click="handleCapitalize"
                :loading="loading"
                :disabled="!textInput.trim()"
              >
                首字母大写
              </el-button>
              <el-button 
                @click="clearInput('text')"
                :disabled="!textInput.trim()"
              >
                清空
              </el-button>
            </template>

            <template #result>
              <div v-if="textOutput" class="result-display">
                <h4>处理结果：</h4>
                <el-input
                  v-model="textOutput"
                  type="textarea"
                  :rows="8"
                  readonly
                  show-word-limit
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyOutput('text')">
                    复制结果
                  </el-button>
                  <el-button @click="clearOutput('text')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- 文本加密标签页 -->
        <el-tab-pane label="文本加密" name="encrypt">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="encrypt-section">
                <el-form label-width="100px">
                  <el-form-item label="输入文本">
                    <el-input
                      v-model="encryptInput"
                      type="textarea"
                      :rows="6"
                      placeholder="请输入要编码/解码的文本..."
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleBase64Encode"
                :loading="loading"
                :disabled="!encryptInput.trim()"
              >
                Base64编码
              </el-button>
              <el-button 
                type="success" 
                @click="handleBase64Decode"
                :loading="loading"
                :disabled="!encryptInput.trim()"
              >
                Base64解码
              </el-button>
              <el-button 
                type="warning" 
                @click="handleUrlEncode"
                :loading="loading"
                :disabled="!encryptInput.trim()"
              >
                URL编码
              </el-button>
              <el-button 
                type="info" 
                @click="handleUrlDecode"
                :loading="loading"
                :disabled="!encryptInput.trim()"
              >
                URL解码
              </el-button>
            </template>

            <template #result>
              <div v-if="encryptOutput" class="result-display">
                <h4>转换结果：</h4>
                <el-input
                  v-model="encryptOutput"
                  type="textarea"
                  :rows="6"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyOutput('encrypt')">
                    复制结果
                  </el-button>
                  <el-button @click="clearOutput('encrypt')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- Markdown转换标签页 -->
        <el-tab-pane label="Markdown转换" name="markdown">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="markdown-section">
                <el-form label-width="100px">
                  <el-form-item label="Markdown">
                    <el-input
                      v-model="markdownInput"
                      type="textarea"
                      :rows="10"
                      placeholder="请输入Markdown文本..."
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleMarkdownToHtml"
                :loading="loading"
                :disabled="!markdownInput.trim()"
              >
                转HTML
              </el-button>
              <el-button 
                type="success" 
                @click="handleMarkdownToText"
                :loading="loading"
                :disabled="!markdownInput.trim()"
              >
                转纯文本
              </el-button>
              <el-button 
                @click="previewMarkdown"
                :disabled="!markdownOutput"
              >
                预览效果
              </el-button>
            </template>

            <template #result>
              <div v-if="markdownOutput" class="markdown-result">
                <el-tabs v-model="markdownTab">
                  <el-tab-pane label="HTML代码" name="html">
                    <el-input
                      v-model="markdownOutput"
                      type="textarea"
                      :rows="8"
                      readonly
                    />
                    <div class="result-actions">
                      <el-button type="success" @click="copyOutput('markdown')">
                        复制HTML
                      </el-button>
                      <el-button @click="clearOutput('markdown')">
                        清空结果
                      </el-button>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="预览效果" name="preview">
                    <div class="markdown-preview" v-html="markdownHtml"></div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- 文本优化标签页 -->
        <el-tab-pane label="文本优化" name="optimize">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="optimize-section">
                <el-form label-width="100px">
                  <el-form-item label="输入文本">
                    <el-input
                      v-model="optimizeInput"
                      type="textarea"
                      :rows="8"
                      placeholder="请输入需要优化的文本..."
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleRemoveDuplicates"
                :loading="loading"
                :disabled="!optimizeInput.trim()"
              >
                去重
              </el-button>
              <el-button 
                type="success" 
                @click="handleSortLines"
                :loading="loading"
                :disabled="!optimizeInput.trim()"
              >
                行排序
              </el-button>
              <el-button 
                type="warning" 
                @click="handleTrimLines"
                :loading="loading"
                :disabled="!optimizeInput.trim()"
              >
                去除空行
              </el-button>
              <el-button 
                type="info" 
                @click="handleReverseLines"
                :loading="loading"
                :disabled="!optimizeInput.trim()"
              >
                行反转
              </el-button>
            </template>

            <template #result>
              <div v-if="optimizeOutput" class="result-display">
                <h4>优化结果：</h4>
                <el-input
                  v-model="optimizeOutput"
                  type="textarea"
                  :rows="8"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyOutput('optimize')">
                    复制结果
                  </el-button>
                  <el-button @click="clearOutput('optimize')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>
      </template>
    </ToolContainer>

    <!-- 功能介绍组件 -->
    <FeatureIntro
      :title="featureConfig.title"
      :description="featureConfig.description"
      :header-icon="featureConfig.headerIcon"
      :features="featureConfig.features"
      :initial-visible="showIntro"
      @close="showIntro = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import { marked } from 'marked'
import ToolContainer from '@/components/ToolContainer.vue'
import ToolSection from '@/components/ToolSection.vue'
import FeatureIntro from '@/components/FeatureIntro.vue'
import { featuresConfig } from '@/config/featuresConfig.js'

// 基础数据
const loading = ref(false)
const showIntro = ref(true)
const featureConfig = featuresConfig.textTools
const markdownTab = ref('html')

// 文本格式化相关
const textInput = ref('')
const textOutput = ref('')

// 文本加密相关
const encryptInput = ref('')
const encryptOutput = ref('')

// Markdown转换相关
const markdownInput = ref('')
const markdownOutput = ref('')
const markdownHtml = ref('')

// 文本优化相关
const optimizeInput = ref('')
const optimizeOutput = ref('')

// 事件处理
function handleTabChange(tabName: string) {
  console.log('切换到标签页:', tabName)
}

// 文本格式化功能
function handleToUpperCase() {
  if (!textInput.value.trim()) {
    ElMessage.warning('请输入要处理的文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    textOutput.value = textInput.value.toUpperCase()
    loading.value = false
    ElMessage.success('转换完成')
  }, 300)
}

function handleToLowerCase() {
  if (!textInput.value.trim()) {
    ElMessage.warning('请输入要处理的文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    textOutput.value = textInput.value.toLowerCase()
    loading.value = false
    ElMessage.success('转换完成')
  }, 300)
}

function handleCapitalize() {
  if (!textInput.value.trim()) {
    ElMessage.warning('请输入要处理的文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    textOutput.value = textInput.value.replace(/\b\w/g, char => char.toUpperCase())
    loading.value = false
    ElMessage.success('转换完成')
  }, 300)
}

// 文本加密功能
function handleBase64Encode() {
  if (!encryptInput.value.trim()) {
    ElMessage.warning('请输入要编码的文本')
    return
  }
  loading.value = true
  try {
    setTimeout(() => {
      encryptOutput.value = btoa(unescape(encodeURIComponent(encryptInput.value)))
      loading.value = false
      ElMessage.success('编码完成')
    }, 300)
  } catch (error) {
    loading.value = false
    ElMessage.error('编码失败：' + error.message)
  }
}

function handleBase64Decode() {
  if (!encryptInput.value.trim()) {
    ElMessage.warning('请输入要解码的文本')
    return
  }
  loading.value = true
  try {
    setTimeout(() => {
      encryptOutput.value = decodeURIComponent(escape(atob(encryptInput.value)))
      loading.value = false
      ElMessage.success('解码完成')
    }, 300)
  } catch (error) {
    loading.value = false
    ElMessage.error('解码失败：' + error.message)
  }
}

function handleUrlEncode() {
  if (!encryptInput.value.trim()) {
    ElMessage.warning('请输入要编码的文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    encryptOutput.value = encodeURIComponent(encryptInput.value)
    loading.value = false
    ElMessage.success('编码完成')
  }, 300)
}

function handleUrlDecode() {
  if (!encryptInput.value.trim()) {
    ElMessage.warning('请输入要解码的文本')
    return
  }
  loading.value = true
  try {
    setTimeout(() => {
      encryptOutput.value = decodeURIComponent(encryptInput.value)
      loading.value = false
      ElMessage.success('解码完成')
    }, 300)
  } catch (error) {
    loading.value = false
    ElMessage.error('解码失败：' + error.message)
  }
}

// Markdown转换功能
function handleMarkdownToHtml() {
  if (!markdownInput.value.trim()) {
    ElMessage.warning('请输入Markdown文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    markdownOutput.value = marked(markdownInput.value)
    markdownHtml.value = markdownOutput.value
    loading.value = false
    ElMessage.success('转换完成')
  }, 300)
}

function handleMarkdownToText() {
  if (!markdownInput.value.trim()) {
    ElMessage.warning('请输入Markdown文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    const html = marked(markdownInput.value)
    const tempDiv = document.createElement('div')
    tempDiv.innerHTML = html
    markdownOutput.value = tempDiv.textContent || tempDiv.innerText || ''
    loading.value = false
    ElMessage.success('转换完成')
  }, 300)
}

function previewMarkdown() {
  markdownTab.value = 'preview'
}

// 文本优化功能
function handleRemoveDuplicates() {
  if (!optimizeInput.value.trim()) {
    ElMessage.warning('请输入要处理的文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    const lines = optimizeInput.value.split('\n')
    const uniqueLines = [...new Set(lines)]
    optimizeOutput.value = uniqueLines.join('\n')
    loading.value = false
    ElMessage.success('去重完成')
  }, 300)
}

function handleSortLines() {
  if (!optimizeInput.value.trim()) {
    ElMessage.warning('请输入要处理的文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    const lines = optimizeInput.value.split('\n')
    const sortedLines = lines.sort()
    optimizeOutput.value = sortedLines.join('\n')
    loading.value = false
    ElMessage.success('排序完成')
  }, 300)
}

function handleTrimLines() {
  if (!optimizeInput.value.trim()) {
    ElMessage.warning('请输入要处理的文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    const lines = optimizeInput.value.split('\n')
    const trimmedLines = lines.filter(line => line.trim() !== '')
    optimizeOutput.value = trimmedLines.join('\n')
    loading.value = false
    ElMessage.success('去除空行完成')
  }, 300)
}

function handleReverseLines() {
  if (!optimizeInput.value.trim()) {
    ElMessage.warning('请输入要处理的文本')
    return
  }
  loading.value = true
  setTimeout(() => {
    const lines = optimizeInput.value.split('\n')
    const reversedLines = lines.reverse()
    optimizeOutput.value = reversedLines.join('\n')
    loading.value = false
    ElMessage.success('反转完成')
  }, 300)
}

// 工具函数
function clearInput(type: string) {
  switch (type) {
    case 'text':
      textInput.value = ''
      break
    case 'encrypt':
      encryptInput.value = ''
      break
    case 'markdown':
      markdownInput.value = ''
      break
    case 'optimize':
      optimizeInput.value = ''
      break
  }
  ElMessage.info('已清空输入')
}

function clearOutput(type: string) {
  switch (type) {
    case 'text':
      textOutput.value = ''
      break
    case 'encrypt':
      encryptOutput.value = ''
      break
    case 'markdown':
      markdownOutput.value = ''
      markdownHtml.value = ''
      break
    case 'optimize':
      optimizeOutput.value = ''
      break
  }
  ElMessage.info('已清空结果')
}

function copyOutput(type: string) {
  let text = ''
  switch (type) {
    case 'text':
      text = textOutput.value
      break
    case 'encrypt':
      text = encryptOutput.value
      break
    case 'markdown':
      text = markdownOutput.value
      break
    case 'optimize':
      text = optimizeOutput.value
      break
  }
  
  if (text) {
    navigator.clipboard.writeText(text)
    ElMessage.success('结果已复制到剪贴板')
  } else {
    ElMessage.warning('没有可复制的内容')
  }
}
</script>

<style scoped>
.text-tools {
  position: relative;
}

.text-input-section,
.encrypt-section,
.markdown-section,
.optimize-section {
  width: 100%;
}

.result-display {
  width: 100%;
}

.result-display h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary, #303133);
}

.result-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.markdown-result {
  width: 100%;
}

.markdown-preview {
  padding: 16px;
  background: var(--el-bg-color-page, #fafbfc);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter, #f2f6fc);
  min-height: 200px;
  line-height: 1.6;
}

.markdown-preview h1,
.markdown-preview h2,
.markdown-preview h3 {
  margin: 16px 0 8px 0;
  color: var(--el-text-color-primary, #303133);
}

.markdown-preview h1 {
  font-size: 24px;
  border-bottom: 2px solid var(--el-border-color, #dcdfe6);
  padding-bottom: 8px;
}

.markdown-preview h2 {
  font-size: 20px;
  border-bottom: 1px solid var(--el-border-color-light, #e4e7ed);
  padding-bottom: 4px;
}

.markdown-preview h3 {
  font-size: 18px;
}

.markdown-preview blockquote {
  margin: 16px 0;
  padding: 8px 16px;
  background: var(--el-color-info-light-9, #f4f4f5);
  border-left: 4px solid var(--el-color-info, #909399);
  color: var(--el-text-color-regular, #606266);
}

.markdown-preview strong {
  font-weight: 600;
  color: var(--el-text-color-primary, #303133);
}

.markdown-preview em {
  font-style: italic;
  color: var(--el-text-color-regular, #606266);
}

.markdown-preview img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 8px 0;
}

.markdown-preview a {
  color: var(--el-color-primary, #409eff);
  text-decoration: none;
}

.markdown-preview a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .result-actions {
    flex-direction: column;
  }
}
</style> 